package dnl.toolbox.files;

import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.net.URL;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;

import de.schlichtherle.io.File;

/**
 * 
 * @author Daniel Orr
 * 
 */
public class ResourceUtils {

	public static String getResourceAsString(Class refClass, String resource) throws IOException {
		InputStream is = refClass.getResourceAsStream(resource);
		if (is == null)
			return null;
		return IOUtils.toString(is);
	}

	/**
	 * Given a resource directory returns all resources in it.
	 * 
	 * @param dirPath
	 * @return
	 */
	public static String[] listResourcesInResourceDirectory(String dirPath) {
		URL url = ClassLoader.getSystemResource(dirPath);
		if (url == null)
			return new String[] {};
		try {
			File dir = new File(url.toURI());
			return dir.list();
		} catch (URISyntaxException e) {
			throw new IllegalStateException(e.getMessage());
		}
	}

	public static File getClassOrigin(Class clazz) {
		String className = clazz.getName();
		className = StringUtils.replace(className, ".", "/");
		className += ".class";
		URL url = clazz.getClassLoader().getResource(className);
		String urlStr = url.toString();
		urlStr = StringUtils.replace(urlStr, "/" + className, "");
		urlStr = StringUtils.replace(urlStr, "jar:", "");
		urlStr = StringUtils.replace(urlStr, "file:", "");
		if (urlStr.endsWith("!")) {
			urlStr = urlStr.substring(0, urlStr.length() - 1);
		}
		return new File(urlStr);
	}

}
